import 'package:magma/heartbeat/helpers/magma_constant.dart';
import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/event_model.dart';

/// 聚会组织者
class GatheringOrganizer extends BaseViewModel {
  // 聚会列表（模拟数据库）
  final List<GatheringModel> _gatherings = [];

  // 聚会评论列表
  final List<GatheringCommentModel> _comments = [];

  /// 获取所有聚会
  List<GatheringModel> get gatherings => List.from(_gatherings);

  /// 根据活动ID获取评论
  List<GatheringCommentModel> getCommentsByGatheringId(String gatheringId) {
    return _comments
        .where((comment) => comment.gatheringId == gatheringId)
        .toList();
  }

  /// 初始化默认聚会数据
  void initializeDefaultGatherings() {
    _gatherings.clear();
    _gatherings.addAll(_getDefaultGatherings());
    _initializeDefaultComments();
  }

  /// 获取默认聚会数据
  List<GatheringModel> _getDefaultGatherings() {
    return [
      GatheringModel(
        id: '1',
        title: 'Let\'s ignite our steps and run towards endless possibilities!',
        description:
            'Bring your passion and join countless other runners on the marathon track. From start to finish, every step is a testament to breakthroughs and perseverance. Join us and write your own legendary story with your own steps! 🏃‍♂️🔥',
        image: MagmaConstant.event1,
        startTime: DateTime.now().add(const Duration(days: 7)),
        endTime: DateTime.now().add(const Duration(days: 7, hours: 3)),
        location: 'Central Park, New York',
      ),
      GatheringModel(
        id: '2',
        title:
            'Measure the city with your steps, surpass yourself with courage!',
        description:
            'This is a journey that blends the charm of the city with the spirit of sports. Whether you\'re a challenger or someone who enjoys running, every step forward will make you stronger. Embrace the challenge and conquer the marathon!',
        image: MagmaConstant.event2,
        startTime: DateTime.now().add(const Duration(days: 14)),
        endTime: DateTime.now().add(const Duration(days: 14, hours: 2)),
        location: 'Mountain Trail, California',
      ),
      GatheringModel(
        id: '3',
        title: 'A marathon isn\'t just about victory at the finish line!',
        description:
            'Every marathon is a testament to our inner perseverance and hard work. From now on, train, strive, and finally cross the finish line. With determination and courage, make the entire journey your road to glory! 🏅✨',
        image: MagmaConstant.event3,
        startTime: DateTime.now().add(const Duration(days: 21)),
        endTime: DateTime.now().add(const Duration(days: 21, hours: 1)),
        location: 'Downtown District, Chicago',
      ),
      GatheringModel(
        id: '4',
        title: 'Challenge your limits and run for your dreams!',
        description:
            'Join this passionate marathon event, push your physical and mental limits, and run at full speed for your dreams. Whether it\'s a long run of tens of kilometers or a short, fun race, this marathon will ignite the fighting spirit in you!',
        image: MagmaConstant.event4,
        startTime: DateTime.now().add(const Duration(days: 28)),
        endTime: DateTime.now().add(const Duration(days: 28, hours: 4)),
        location: 'Santa Monica Beach, California',
      ),
      GatheringModel(
        id: '5',
        title: 'Cross the other side and set your own new record!',
        description:
            'Are you ready to set a new record for yourself? Cross every kilometer of the course, pushing your limits with unwavering determination and unwavering perseverance, and share your moments of achievement with other runners. The finish line awaits you!',
        image: MagmaConstant.event5,
        startTime: DateTime.now().add(const Duration(days: 35)),
        endTime: DateTime.now().add(const Duration(days: 35, hours: 2)),
        location: 'Riverside Park, Miami',
      ),
    ];
  }

  /// 初始化默认评论数据
  void _initializeDefaultComments() {
    _comments.clear();
    _comments.addAll(_getDefaultComments());
  }

  /// 获取默认评论数据
  List<GatheringCommentModel> _getDefaultComments() {
    return [
      // 活动1的评论
      GatheringCommentModel(
        id: '1',
        gatheringId: '1',
        userId: '1',
        content:
            'This marathon event looks amazing! I\'m so excited to participate and challenge myself. The description really motivates me to push my limits! 🔥',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      GatheringCommentModel(
        id: '2',
        gatheringId: '1',
        userId: '2',
        content:
            'I\'ve been training for months for this event. The passion in the description matches exactly how I feel about running. Can\'t wait to write my own legendary story!',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      GatheringCommentModel(
        id: '3',
        gatheringId: '1',
        userId: '3',
        content:
            'This will be my first marathon! The encouragement in the description gives me confidence. Looking forward to meeting other passionate runners!',
        createdAt: DateTime.now().subtract(const Duration(hours: 12)),
      ),
      GatheringCommentModel(
        id: '4',
        gatheringId: '1',
        userId: '4',
        content:
            'The energy in this event description is contagious! I love how it emphasizes both breakthroughs and perseverance. This is exactly what I need right now.',
        createdAt: DateTime.now().subtract(const Duration(hours: 6)),
      ),
      GatheringCommentModel(
        id: '5',
        gatheringId: '1',
        userId: '5',
        content:
            'Perfect timing for this event! I\'ve been looking for something to reignite my passion for running. The description speaks to my soul!',
        createdAt: DateTime.now().subtract(const Duration(hours: 3)),
      ),

      // 活动2的评论
      GatheringCommentModel(
        id: '6',
        gatheringId: '2',
        userId: '6',
        content:
            'City running combined with sports spirit - this is exactly what I\'ve been looking for! The urban challenge aspect really appeals to me.',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      GatheringCommentModel(
        id: '7',
        gatheringId: '2',
        userId: '7',
        content:
            'I love how this event blends city charm with athletic spirit. Every step forward making us stronger - that\'s the mindset I need!',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      GatheringCommentModel(
        id: '8',
        gatheringId: '2',
        userId: '8',
        content:
            'Whether you\'re a challenger or enjoy running - this description includes everyone. I appreciate the inclusive approach!',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      GatheringCommentModel(
        id: '9',
        gatheringId: '2',
        userId: '9',
        content:
            'The courage to surpass yourself - that\'s what I need right now. This event seems perfect for breaking through my current plateau.',
        createdAt: DateTime.now().subtract(const Duration(hours: 18)),
      ),
      GatheringCommentModel(
        id: '10',
        gatheringId: '2',
        userId: '10',
        content:
            'Measuring the city with steps sounds poetic and powerful. I\'m ready to embrace this challenge and conquer the marathon!',
        createdAt: DateTime.now().subtract(const Duration(hours: 9)),
      ),

      // 活动3的评论
      GatheringCommentModel(
        id: '11',
        gatheringId: '3',
        userId: '1', // Zephyr
        content:
            'This description really captures the essence of marathon running! It\'s not just about the finish line, but the entire journey of perseverance.',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      GatheringCommentModel(
        id: '12',
        gatheringId: '3',
        userId: '2', // Nexus
        content:
            'The emphasis on inner perseverance and hard work resonates with me deeply. This is what marathon training is all about!',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      GatheringCommentModel(
        id: '13',
        gatheringId: '3',
        userId: '3', // Vortex
        content:
            'Determination and courage to make the entire journey your road to glory - that\'s exactly the mindset I want to develop!',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      GatheringCommentModel(
        id: '14',
        gatheringId: '3',
        userId: '4', // Prism
        content:
            'From training to striving to crossing the finish line - this describes my marathon journey perfectly. I\'m ready for this challenge!',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      GatheringCommentModel(
        id: '15',
        gatheringId: '3',
        userId: '5', // Cipher
        content:
            'The road to glory through determination - this event description motivates me to push beyond my comfort zone!',
        createdAt: DateTime.now().subtract(const Duration(hours: 15)),
      ),

      // 活动4的评论
      GatheringCommentModel(
        id: '16',
        gatheringId: '4',
        userId: '6', // Quantum
        content:
            'Challenging limits and running for dreams - this is exactly what I need! The passionate description really speaks to my heart.',
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      GatheringCommentModel(
        id: '17',
        gatheringId: '4',
        userId: '7', // Matrix
        content:
            'Pushing physical and mental limits at full speed for dreams - this captures the true spirit of marathon running!',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      GatheringCommentModel(
        id: '18',
        gatheringId: '4',
        userId: '8', // Phantom
        content:
            'Whether long runs or short fun races, this marathon will ignite fighting spirit - I love the variety and inclusivity!',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      GatheringCommentModel(
        id: '19',
        gatheringId: '4',
        userId: '9', // Zenith
        content:
            'The fighting spirit ignition is exactly what I\'ve been missing in my training. This event sounds perfect for reigniting my passion!',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      GatheringCommentModel(
        id: '20',
        gatheringId: '4',
        userId: '10', // Oracle
        content:
            'Running for dreams with unwavering determination - this description motivates me to sign up immediately!',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),

      // 活动5的评论
      GatheringCommentModel(
        id: '21',
        gatheringId: '5',
        userId: '1', // Zephyr
        content:
            'Setting new records and crossing every kilometer with unwavering determination - this is the challenge I\'ve been waiting for!',
        createdAt: DateTime.now().subtract(const Duration(days: 6)),
      ),
      GatheringCommentModel(
        id: '22',
        gatheringId: '5',
        userId: '2', // Nexus
        content:
            'The finish line awaits! This description builds such anticipation and excitement. I\'m ready to push my limits!',
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      GatheringCommentModel(
        id: '23',
        gatheringId: '5',
        userId: '3', // Vortex
        content:
            'Sharing moments of achievement with other runners - this community aspect is what makes marathon events special!',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      GatheringCommentModel(
        id: '24',
        gatheringId: '5',
        userId: '4', // Prism
        content:
            'Unwavering perseverance to set new records - this event description perfectly captures my marathon goals!',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      GatheringCommentModel(
        id: '25',
        gatheringId: '5',
        userId: '5', // Cipher
        content:
            'Crossing every kilometer with determination - this is exactly the mindset I need to achieve my personal best!',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
    ];
  }

  /// 根据ID获取聚会
  GatheringModel? fetchGatheringById(String gatheringId) {
    try {
      return _gatherings.firstWhere((gathering) => gathering.id == gatheringId);
    } catch (e) {
      return null;
    }
  }

  /// 搜索聚会
  List<GatheringModel> exploreGatherings(String keyword) {
    if (keyword.isEmpty) return gatherings;

    return _gatherings.where((gathering) {
      return gathering.title.toLowerCase().contains(keyword.toLowerCase()) ||
          gathering.description.toLowerCase().contains(keyword.toLowerCase()) ||
          gathering.location.toLowerCase().contains(keyword.toLowerCase());
    }).toList();
  }

  /// 添加聚会评论
  Future<bool> submitGatheringComment(
    String gatheringId,
    String userId,
    String content,
  ) async {
    setBusy(true);
    try {
      if (content.trim().isEmpty) {
        setError('Comment content cannot be empty');
        return false;
      }

      // 验证聚会存在
      final gathering = fetchGatheringById(gatheringId);
      if (gathering == null) {
        setError('Gathering not found');
        return false;
      }

      // 创建评论记录
      final comment = GatheringCommentModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        gatheringId: gatheringId,
        userId: userId,
        content: content.trim(),
        createdAt: DateTime.now(),
      );

      _comments.add(comment);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 获取聚会的所有评论
  List<GatheringCommentModel> retrieveGatheringComments(String gatheringId) {
    return _comments
        .where((comment) => comment.gatheringId == gatheringId)
        .toList();
  }

  /// 获取用户的评论
  List<GatheringCommentModel> fetchUserComments(String userId) {
    return _comments.where((comment) => comment.userId == userId).toList();
  }

  /// 删除评论
  Future<bool> removeComment(String commentId, String userId) async {
    setBusy(true);
    try {
      final index = _comments.indexWhere(
        (comment) => comment.id == commentId && comment.userId == userId,
      );

      if (index == -1) {
        setError(
          'Comment not found or you do not have permission to delete it',
        );
        return false;
      }

      _comments.removeAt(index);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }
}
